package com.myway.controller;

import com.alibaba.fastjson.JSON;
import com.myway.dto.common.JsonData;
import com.myway.dto.domain.Cabin;
import com.myway.dto.domain.FlightCriteria;
import com.myway.dto.domain.GlobalResult;
import com.myway.dto.domain.TotalFlyPrice;
import com.myway.dto.ibe_param.FlightParam;
import com.myway.dto.ibe_param.TicketPrice;
import com.myway.dto.vo.FlySegmentVo;
import com.myway.service.FlyService;
import com.myway.service.ibe.command.AVCommand;
import com.myway.utils.UserUtils;
import com.myway.pojo.FlyOrder;
import com.myway.service.AVService;
import com.myway.service.CountPriceService;
import com.travelsky.util.QDateTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yufei on 2018/4/2.
 */
@Controller
@RequestMapping("/en/av")
@Slf4j
public class AVControllerEn {

    @Autowired
    private AVService avService;

    @Autowired
    private CountPriceService countPriceService;

    @Autowired
    private FlyService flyService;

    @Autowired
    private AVCommand avCommand;



    /**
     * 系统首页订票登录，需要跳转页面。
     * @param
     * @param
     * @param
     * @return
     * @throws
     */
    @RequestMapping("/flights")
    @ResponseBody
    public ModelAndView  searchFilghts(HttpServletRequest request,FlightCriteria Criteria)throws Exception{
        Criteria.setOrgCn(new String (Criteria.getOrgCn().getBytes("iso-8859-1"),"utf-8"));
        Criteria.setDstCn(new String (Criteria.getDstCn().getBytes("iso-8859-1"),"utf-8"));
        ModelAndView modelAndView = new ModelAndView();

        String  calenderStr = avService.searchCalenderFlight(Criteria);
        GlobalResult globalResult=null;
        if(!StringUtils.isEmpty(Criteria.getTravlType())&&Criteria.getTravlType().equals("rt")){
            globalResult= avService.searchRoundTripFlight(Criteria);
        }else{
            globalResult= avService.searchFlight(Criteria);
        }
        //avService.searchCalenderFlight(Criteria);
        //如果为空，则返回基本输入信息，
        if(globalResult!=null){
            String result=JSON.toJSONString(globalResult);
            modelAndView.addObject("segmentlist",globalResult.getData1());//航段信息
            modelAndView.addObject("multicabinCombos",globalResult.getData());//舱位价格
            log.info("========@@@@@=============="+JSON.toJSON(globalResult.getData1()));
            request.getSession().setAttribute("flghts",globalResult.getData1());

        }
        modelAndView.addObject("Criteria",Criteria);

        log.info("================  "+ JSON.toJSON(calenderStr));

        modelAndView.addObject("calendermap", calenderStr);
        modelAndView.setViewName("/en/tickets");
        return modelAndView;
    }

    /**
     * 跳转立即预定页面
     * @param request
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/orderflights")
    @ResponseBody
    public ModelAndView  orderFilghts(HttpServletRequest request, FlightParam param, String orgCityCn, String dstCityCn, String flightNoRt, String flightDateRt, String arrDateRt, String travlType) throws Exception {

        String DepTerm=new String (orgCityCn.getBytes("iso-8859-1"),"utf-8");
        String ArriTerm=new String (dstCityCn.getBytes("iso-8859-1"),"utf-8");
        ModelAndView modelAndView = new ModelAndView();
        String str =(String)request.getSession().getAttribute("userType");
        if(str !=null){
            if(!StringUtils.isEmpty(travlType)){
                param.setTravlType(travlType.toUpperCase());
            }
            param.setCurrency("EUR");
            param.setFlightNo(param.getFlightNo().trim());
            List<FlightParam> params=new ArrayList<FlightParam>();
            params.add(param);
            if(!StringUtils.isEmpty(travlType)&&travlType.equals("rt")){
                FlightParam param1=new FlightParam();
                BeanUtils.copyProperties(param,param1);
                param1.setOrgCity(param.getDstCity());
                param1.setDstCity(param.getOrgCity());
                param1.setFlightNo(flightNoRt.trim());
                param1.setFlightDate(flightDateRt);
                param1.setArrDate(arrDateRt);
                params.add(param1);
            }
            Map map = countPriceService.findCabinTypePrice(params);
            modelAndView.addObject("param",map.get("param"));
            String flightDateQ = (param.getFlightDate().replace("T", " ")).substring(0, 16);
            String arrDateQ = (param.getArrDate().replace("T", " ")).substring(0, 16);
            modelAndView.addObject("flightDateQ",flightDateQ);
            modelAndView.addObject("arrDateQ",arrDateQ);

            modelAndView.addObject("DepTerm",DepTerm);
            modelAndView.addObject("ArriTerm",ArriTerm);
            request.getSession().setAttribute("priceSession",map.get("cabinTypePrice"));//票价放入session
            modelAndView.addObject("cabinTypePrice",map.get("cabinTypePrice"));//税费
            modelAndView.addObject("totalFlyPrice",map.get("totalFlyPrice"));//机票价
            modelAndView.addObject("currency",param.getCurrency());
            modelAndView.addObject("travlType",travlType.toUpperCase());

            List<FlySegmentVo> flySegmentVoList=new ArrayList<>();
            FlySegmentVo flySegmentVo=new FlySegmentVo();
            flySegmentVo.setTravlType(travlType.toUpperCase());
            flySegmentVo.setCurrency(param.getCurrency());
            flySegmentVo.setDepCode(param.getOrgCity());
            flySegmentVo.setDepCodeName(DepTerm);
            flySegmentVo.setDepTime(QDateTime.stringToDate(param.getFlightDate(),"yyyy-mm-ddThh:mi:ss"));
            flySegmentVo.setArrCode(param.getDstCity());
            flySegmentVo.setArrCodeName(ArriTerm);
            flySegmentVo.setArrTime(QDateTime.stringToDate(param.getArrDate(),"yyyy-mm-ddThh:mi:ss"));
            flySegmentVo.setCabinClass(param.getCabinCode());
            flySegmentVo.setFlightNo(param.getAirline()+param.getFlightNo());
//            flySegmentVo.setBaseFare(new BigDecimal(487.0));
            flySegmentVoList.add(flySegmentVo);

            if(!StringUtils.isEmpty(travlType)&&travlType.equals("rt")){
                FlySegmentVo flySegmentVo1=new FlySegmentVo();
                flySegmentVo1.setTravlType(travlType.toUpperCase());
                flySegmentVo1.setCurrency(param.getCurrency());
                flySegmentVo1.setDepCode(param.getDstCity());
                flySegmentVo1.setDepCodeName(ArriTerm);
                flySegmentVo1.setDepTime(QDateTime.stringToDate(flightDateRt,"yyyy-mm-ddThh:mi:ss"));
                flySegmentVo1.setArrCode(param.getOrgCity());
                flySegmentVo1.setArrCodeName(DepTerm);
                flySegmentVo1.setArrTime(QDateTime.stringToDate(arrDateRt,"yyyy-mm-ddThh:mi:ss"));
                flySegmentVo1.setCabinClass(param.getCabinCode());
                flySegmentVo1.setFlightNo(param.getAirline()+flightNoRt);
                flySegmentVo1.setTravlType(param.getTravlType());
//                flySegmentVo1.setBaseFare(new BigDecimal(490.0));
                flySegmentVoList.add(flySegmentVo1);
            }
            modelAndView.addObject("flySegmentVoList",flySegmentVoList);
            modelAndView.setViewName("/en/fillMsg");
        }else{
            modelAndView.setViewName("/en/login");
        }
        return modelAndView;
    }



    /**
     * 添加旅客订单
     * @param passageList
     * @return
     */
    @RequestMapping("/countprice")
    @ResponseBody
    public JsonData countAmount(String passageList, String taxList, TotalFlyPrice totalFlyPrice){
        Map map = countPriceService.countAmount(passageList, taxList, totalFlyPrice);
        return JsonData.success(map);
    }

    /**
     * 添加旅客订单
     * @param flyOrder
     * @return
     */
    @RequestMapping("/addflight")
    @ResponseBody
    public JsonData addFlyOrder(HttpServletRequest request, FlightParam param, String passgaeData, FlyOrder flyOrder){
        //从session中取出当前返回的价格list
        TicketPrice priceList =(TicketPrice)request.getSession().getAttribute("priceSession");
        String userId = UserUtils.getUserId();
        flyOrder.setUserId(userId);
        JsonData jsonData = avService.searchFlyOrder(param, passgaeData, flyOrder, priceList);
        //预定之后删除session
        //request.getSession().removeAttribute("priceSession");
        return jsonData;
    }

}